package com.ds.infra.ibatis.transaction.jdbc;

import com.ds.infra.ibatis.transaction.Transaction;
import com.ds.infra.ibatis.transaction.TransactionFactory;
import com.ds.infra.ibatis.transaction.TransactionIsolationLevel;
import lombok.RequiredArgsConstructor;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@RequiredArgsConstructor
public class JdbcTransactionFactory implements TransactionFactory {

    private final DataSource dataSource;

    @Override
    public Transaction newTransaction(DataSource dataSource) {
        return newTransaction(dataSource, null);
    }

    @Override
    public Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level) {
        try {
            Connection connection = dataSource.getConnection();
            if (level != null) {
                connection.setTransactionIsolation(level.getLevel());
            }
            return new JdbcTransaction(connection);
        } catch (SQLException e) {
            throw new RuntimeException("Error opening JDBC connection", e);
        }
    }
}
